#!/usr/bin/env node

const http=require('http'),
      cp=require('child_process'),
      qs=require('querystring'),
      log=console.log;

let result='';

http.createServer((req,res)=>{
  if(req.url!='/'){
    err(res);
    return;
  }
  
  log(req.headers);
  log('');

  switch(req.method){
    case 'GET':
      showHtml(res);
      break;
    case 'POST':
      execCmd(req,res);
      break;
    default:
      err(res);
      break;
  }

}).listen(8080);


function execCmd(req,res){
  let cmd='';

  req.on('data',chunk=>cmd+=chunk);
  req.on('end',()=>{
    cmd=qs.parse(cmd).cmd;

    if(cmd==''){
      result='Please input linux command';
      showHtml(res);
    }else{
      log(cmd);
      cp.exec(cmd,(err,stdout,stderr)=>{
        result=(err===null)?stdout:stderr;
        showHtml(res);
      });
    }
  });
}



function showHtml(res){
  let html=`
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset='utf8'/>
      <title>linux command</title>
    </head>
    <body>
      <h1>Input a Linux Command</h1>
      <form method='post' action='/'>
        <input type='text' name='cmd' />
        <input type='submit' value='execute' />
      </form>
      <div>
        <pre style="font-family:Consolas;">
        ${result}
        </pre>
      </div>
    </body>
  </html>`;

  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length',Buffer.byteLength(html));
  
  res.statusCode=200;
  res.end(html);

}


function err(res){
  const msg = 'Not found!';

  res.statusCode = 404;
  res.setHeader('Content-Length', msg.length);
  res.setHeader('Content-Type', 'text/plain');

  res.end(msg);
}
